package cn.inyaa.admin.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class InyaaAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Resource
    private ObjectMapper objectMapper; //springmvc启动时自动装配json处理类

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        String msg = "";
        if (e instanceof AccountExpiredException) {
            msg = "账户过期";
            log.error(msg, e);
        } else if (e instanceof CredentialsExpiredException) {
            msg = "证书过期";
            log.error(msg, e);
        } else if (e instanceof DisabledException) {
            msg = "账户不可用";
            log.error(msg, e);
        } else if (e instanceof LockedException) {
            msg = "账户锁定";
            log.error(msg, e);
        } else if (e instanceof InsufficientAuthenticationException) {
            msg = "凭据不信任";
            log.error(msg, e);
        }  else if (e instanceof BadCredentialsException) {
            msg = "密码错误";
            log.error(msg, e);
        }else {
            msg = "系统异常";
            log.error(msg, e);
        }

        Map<String, Object> rsp = new HashMap<>();
        rsp.put("code", HttpStatus.UNAUTHORIZED.value());
        rsp.put("message", msg);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(rsp));
        response.getWriter().flush();
        response.getWriter().close();
    }

}
